<template>
  <div class="apply-dialog">
    <el-dialog
      title=""
      :visible.sync="dialogVisible"
      :fullscreen="true"
      :before-close="handleClose"
      :close-on-click-modal="false"
      :show-close="false"
    >
      <el-dialog
        width="40%"
        title=""
        custom-class="techDialog"
        :visible.sync="remarkVisible"
        :modal="false"
        :close-on-click-modal="false"
        append-to-body
      >
        <div slot="title" class="clearfix mt30">
          <div class="font16 width150 pt3">选择阶段评审审批人</div>
          <el-select
            v-model="secProcessor"
            filterable
            placeholder="选择审批人"
            size="small"
            style="width: 30%;margin-top:10px"
          >
            <el-option
              v-for="(item, index) in users"
              :key="index"
              :label="item.nickName"
              :value="item.userId"
            />
          </el-select>
        </div>

        <div slot="footer">
          <div class="btn-list mr50">
            <template v-for="(item, index) in processStructureValue.edges">
              <el-button
                v-if="
                  processStructureValue.workOrder.is_end === 0 &&
                    item.source === currentNode.id
                "
                :key="index"
                size="mini"
                type="primary"
                @click="submitAction(item)"
              >
                {{ item.label }}
              </el-button>
            </template>
          </div>
        </div>
      </el-dialog>
      <div slot="title" class="flex flex-row align-center justify-content-end">
        <div class="btn-list flex flex-row align-center">
          <template v-for="(item, index) in processStructureValue.edges">
            <el-button
              v-if="
                processStructureValue.workOrder.is_end === 0 &&
                  item.source === currentNode.id
              "
              :key="index"
              size="mini"
              type="primary"
              @click="remarkVisible = true"
            >
              {{ item.label }}
            </el-button>
          </template>

          <el-button type="primary" size="mini" @click="handlePrint(printData)">
            导出PDF
          </el-button>

          <div class="pl15 pr15">
            下发人：<span class="primary-color">{{
              processStructureValue.workOrder.createdName
            }}</span>
          </div>
          <div class="pl15 pr15">
            最新状态：<span class="primary-color">{{
              processStructureValue.workOrder.current_state_name
            }}</span>
            <span
              v-if="processStructureValue.workOrder.principals != ''"
              class="ml20"
            >当前处理人：</span>
            <span
              v-if="processStructureValue.workOrder.principals != ''"
              class="danger-color"
            >【{{ processStructureValue.workOrder.principals }}】</span>
          </div>
          <div class="ml50" @click="handleClose">
            <i class="el-icon-close cursor-p font22 line-height-32" />
          </div>
        </div>
      </div>
      <div class="app-container flex flex-row">
        <div class="left flex-auto">
          <el-form ref="ruleForm" label-width="120px" class="" />
          <div v-if="dialogVisible" id="printFrom" class="text item reviewFrom">
            <template v-for="(tplItem, tplIndex) in processStructureValue.tpls">
              <el-card
                v-show="
                  currentNode.hideTpls === undefined ||
                    currentNode.hideTpls === null ||
                    currentNode.hideTpls.indexOf(tplItem.form_structure.id) ===
                    -1
                "
                :key="tplIndex"
                class="box-card apply-box mb20"
              >
                <div
                  slot="header"
                  class="clearfix flex flex-row align-center height32"
                >
                  <div class="line" />
                  <span class="font16 ml10 flex-auto">{{
                    tplItem.form_name
                  }}</span>
                </div>
                <fm-generate-form
                  :ref="'generateForm-' + tplItem.id"
                  :preview="
                    !!(
                      (currentNode.hideTpls !== undefined &&
                      currentNode.hideTpls !== null &&
                      currentNode.hideTpls.indexOf(
                        tplItem.form_structure.id
                      ) !== -1) ||
                      (currentNode.writeTpls === undefined ||
                      currentNode.writeTpls === null ||
                      currentNode.writeTpls.indexOf(
                        tplItem.form_structure.id
                      ) === -1) ||
                      (isActiveProcessing && currentNode.activeOrder)
                    )
                  "
                  :remote="remoteFunc"
                  :value="tplItem.form_data"
                  :data="tplItem.form_structure"
                >
                  <div
                    slot="blank_1671117855000_61552"
                    class="title flex flex-row text-center justify-content-center align-center font18"
                  >
                    <span>{{ globalConfig.fullName }}医疗技术临床应用情况报告表（ </span>
                    <el-input
                      v-model="tplItem.form_data.year"
                      size="mini"
                      class="width80"
                      :disabled="true"
                    />
                    <span> &nbsp;年度&nbsp; </span>
                    <el-input
                      v-model="tplItem.form_data.quarter"
                      size="mini"
                      class="width65"
                      :disabled="true"
                    />
                    <span> &nbsp;季度）</span>
                  </div>
                </fm-generate-form>
              </el-card>
            </template>
          </div>
        </div>
        <div class="right width320 ml10">
          <el-card class="box-card history-box mb20">
            <div
              slot="header"
              class="clearfix flex flex-row align-center height32"
            >
              <div class="line" />
              <span class="font16 ml10 flex-auto">审批历史</span>
            </div>
            <vue-scroll :ops="ops">
              <div class="timeline">
                <el-timeline v-if="timelineShow">
                  <el-timeline-item
                    v-for="item in timeLine"
                    :key="item.id"
                    :hide-timestamp="true"
                    icon="el-icon-my-time"
                    color="#277fd6"
                    size="large"
                  >
                    <div class="flex flex-column">
                      <div class="time">
                        <span class="text">{{ item.create_time }}</span>
                        <el-tag
                          :type="getHistoryTag(item)"
                          effect="dark"
                          size="small"
                          class="stateTag ml10"
                        >
                          {{ getHistoryState(item) }}
                        </el-tag>
                      </div>
                      <div
                        v-if="item.status == 2 && item.target != ''"
                        class="info"
                      >
                        <span class="label">下发人：</span><span class="detail">{{ item.processor }}</span>
                      </div>
                      <div v-else class="info">
                        <span class="label">审批人：</span><span class="detail">{{ item.processor }}</span>
                      </div>
                      <div class="info">
                        <span class="label">审批节点：</span><span class="detail">{{ item.state }}</span>
                      </div>
                      <div
                        v-if="item.status == 2 && item.target != ''"
                        class="info flex flex-row"
                      />
                      <div v-else class="info flex flex-row">
                        <span class="label">审批意见：</span><span class="detail flex-auto">{{
                          item.remarks
                        }}</span>
                      </div>
                    </div>
                  </el-timeline-item>
                </el-timeline>
                <div v-else class="empty-time mt100">
                  <img src="@/assets/empty.png" alt="">
                  <span>暂时没有审批内容</span>
                </div>
              </div>
            </vue-scroll>
          </el-card>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Vue from 'vue'
import { GenerateForm } from '@/components/VueFormMaking'
import 'form-making/dist/FormMaking.css'
Vue.component(GenerateForm.name, GenerateForm)

import { processStructure, activeOrder } from '@/api/xjs/work-order'
import { handleWorkOrder } from '@/api/xjs/ns-order'
import { listAllUser } from '@/api/system/sysuser'
import { getOrdinaryDeptList } from '@/api/system/dept'
import { mapGetters } from 'vuex'
import printJS from 'print-js'
export default {
  name: 'ApplyDialog',
  components: {},
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      timelineShow: false,
      timeLine: [],
      ops: {
        vuescroll: {
          mode: 'native',
          sizeStrategy: 'percent',
          detectResize: true,
          locking: true
        },
        scrollPanel: {
          maxHeight: 800
        },
        bar: {
          background: '#277fd6',
          size: '3px',
          keepShow: true
        },
        rail: {
          background: '#E0E8F0',
          opacity: 1,
          size: '3px',
          specifyBorderRadius: false,
          gutterOfEnds: '50px',
          gutterOfSide: '0px',
          keepShow: false
        }
      },
      users: [],
      secProcessor: null,
      printData: {
        printable: 'printFrom',
        header: '',
        ignore: ['no-print']
      },
      loading: false,
      dialogVisible: false,
      isLoadingStatus: true,
      remarkVisible: false,
      currentNode: {
        hideTpls: null,
        writeTpls: null
      },
      isActiveProcessing: false,
      tpls: [],
      remarks: '', // 备注信息
      alertMessage: '',
      nodeStepList: [],
      circulationHistoryList: [],
      activeIndex: 0,
      processStructureValue: {
        workOrder: { title: '' }
      },
      ruleForm: {
        title: '',
        projectNo: '',
        process: '',
        classify: '',
        state_id: '',
        state: '',
        source_state: '',
        processor: '',
        process_method: '',
        tpls: [],
        tasks: []
      },
      processId: null,
      workOrderId: null,
      remoteFunc: {
        // 获取用户列表
        async userList(resolve) {
          const res = await listAllUser({})
          const options = res.data
          resolve(options)
        },
        async deptTreeList(resolve) {
          const res = await getOrdinaryDeptList()
          resolve(res.data)
        }
      }
    }
  },
  computed: {
    ...mapGetters(['name', 'userId', 'globalConfig'])
  },
  methods: {
    getHistoryState(item) {
      if (item.circulation == '结束') {
        return '审批完成'
      } else if (item.circulation == '已撤回') {
        return '已撤回'
      } else {
        if (item.status == 2) {
          if (item.target != '') {
            return '阶段评审下发'
          } else {
            return '转交'
          }
        } else if (item.status == 0) {
          return '审批驳回'
        } else {
          return '审批通过'
        }
      }
    },
    getHistoryTag(item) {
      if (item.circulation == '结束') {
        return 'success'
      } else if (item.circulation == '已撤回') {
        return 'danger'
      } else {
        if (item.status == 2) {
          if (item.target != '') {
            return ''
          } else {
            return 'warning'
          }
        } else if (item.status == 0) {
          return 'danger'
        } else {
          return 'success'
        }
      }
    },
    handlePrint(params) {
      printJS({
        maxWidth: 1920,
        documentTitle: `${this.globalConfig.fullName}医务一网通办`,
        printable: params.printable, // 'printFrom',
        type: params.type || 'html',
        header: params.header, // '表单',
        targetStyles: ['*'],
        ignoreElements: params.ignore || [], // ['no-print']
        properties: params.properties || null
      })
    },
    handleClose(val) {
      this.dialogVisible = false
    },
    open(processId, workOrderId) {
      this.processId = processId
      this.workOrderId = workOrderId
      listAllUser({}).then(response => {
        this.users = response.data
      })

      this.getProcessNodeList()
    },

    getProcessNodeList() {
      processStructure({
        processId: this.processId,
        workOrderId: this.workOrderId
      }).then(response => {
        this.isActiveProcessing = false
        this.processStructureValue = response.data
        this.circulationHistoryList = this.processStructureValue.circulationHistory
        if (this.circulationHistoryList.length > 0) {
          this.timelineShow = true
          this.timeLine = this.circulationHistoryList
        }
        // 获取当前展示节点列表
        this.nodeStepList = []
        if (this.processStructureValue.nodes) {
          for (var i = 0; i < this.processStructureValue.nodes.length; i++) {
            if (
              this.processStructureValue.nodes[i].id ===
              this.processStructureValue.workOrder.current_state
            ) {
              // 当前节点
              this.nodeStepList.push(this.processStructureValue.nodes[i])
              this.activeIndex = this.nodeStepList.length - 1
              if (i + 1 === this.processStructureValue.nodes.length) {
                this.activeIndex = this.nodeStepList.length
              }
              this.currentNode = this.processStructureValue.nodes[i]
            } else if (!this.processStructureValue.nodes[i].isHideNode) {
              // 非隐藏节点
              this.nodeStepList.push(this.processStructureValue.nodes[i])
            }
          }
        }

        // 如果回退到初始节点则可编辑。
        if (this.activeIndex === 0 && this.currentNode.clazz === 'start') {
          this.currentNode.writeTpls = []
          for (var tplTmp of this.processStructureValue.tpls) {
            this.currentNode.writeTpls.push(tplTmp.form_structure.id)
          }
        }

        // 判断是否需要主动处理
        for (var stateValue of this.processStructureValue.workOrder.state) {
          if (
            this.processStructureValue.workOrder.current_state ===
              stateValue.id &&
            stateValue.processor.length > 1
          ) {
            this.isActiveProcessing = true
            break
          }
        }
        this.dialogVisible = true
        this.isLoadingStatus = false
      })
    },
    submitAction(item) {
      var promiseList = []
      this.tpls = []
      if (this.secProcessor == null || this.secProcessor < 1) {
        this.$message({
          type: 'warning',
          message: '请填选择审批人'
        })
        return false
      }
      for (var tpl of this.processStructureValue.tpls) {
        this.tpls.push({
          tplDataId: tpl.id,
          tplId: tpl.form_structure.id
        })
        promiseList.push(this.$refs['generateForm-' + tpl.id][0].getData())
      }
      Promise.all(promiseList).then(values => {
        for (var tplDataIndex in this.tpls) {
          this.tpls[tplDataIndex].tplValue = values[tplDataIndex]
        }
        console.log(this.processStructureValue.tpls[0].form_data)
        this.tpls[0].tplValue = Object.assign(
          {},
          this.processStructureValue.tpls[0].form_data,
          this.tpls[0].tplValue
        )
        handleWorkOrder({
          tasks: this.processStructureValue.process.task,
          source_state: this.processStructureValue.workOrder.current_state,
          target_state: item.target,
          circulation: item.label,
          flow_properties:
            item.flowProperties === undefined
              ? 2
              : parseInt(item.flowProperties),
          work_order_id: parseInt(this.workOrderId),
          remarks: this.remarks,
          is_exec_task: item.isExecuteTask,
          tpls: this.tpls,
          projectNo: this.ruleForm.projectNo,
          source_project: this.tpls[0].tplValue['project_id'],
          sec_processor: this.secProcessor
        }).then(response => {
          if (response.code === 200) {
            this.remarkVisible = false
            this.dialogVisible = false
            this.$emit('refreshTable')
          }
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
/* 去掉全选按钮 */
::v-deep .el-table .disabledCheck .cell .el-checkbox__inner {
    display: none !important;
}

::v-deep .el-table .disabledCheck .cell::before {
    content: "请选择";
    text-align: center;
    line-height: 37px;
}
.app-container {
    max-width: 1430px;
    margin: 0 auto;
    background: #ebf4fa;
    border-radius: 12px;
    .apply-box {
        border-radius: 15px;
        .line {
            height: 22px;
            width: 5px;
            background: #277fd6;
        }
    }
    .history-box {
        border-radius: 15px;
        .line {
            height: 22px;
            width: 5px;
            background: #277fd6;
        }
    }
}
</style>
